//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Diagnostics.Contracts;
using System.IO;

namespace OpenLS.Spreadsheet.Formats.Biff.Records
{
    internal class BoolOrErrorRecord : CellValueRecord
    {
        private byte _code;
        private bool _isError;

        public BoolOrErrorRecord(Cell cell, BiffWriterWorkbookContext context): base (cell, context)
        {
            Contract.Requires(cell.Value != null);
            Contract.Requires(cell.Value is bool || cell.Value is Error);
            if (cell.Value is bool)
            {
                bool b = (bool) cell.Value;
                _isError = false;
                _code = (byte) (b ? 1 : 0);
            }
            else
            {
                _isError = true;
                Error error = (Error) cell.Value;
                _code = (byte) error.Type;
            }
        }

        public BoolOrErrorRecord()
        {
        }

        protected override object GetValue(BiffReaderWorkbookContext context)
        {
            if (_isError)
            {
                return Errors.GetError((ErrorType) _code);
            }
            return _code != 0;
        }

        protected override void WriteValue(BinaryWriter writer)
        {
            writer.Write(_code);
            writer.Write(_isError);
        }

        protected override void ReadValue(BinaryReader reader, int length)
        {
            _code = reader.ReadByte();
            _isError = reader.ReadBoolean();
        }

        internal override BiffRecordType RecordType
        {
            get { return BiffRecordType.BoolErr; }
        }
    }
}